package com.yeebo.service.config;

import com.yeebo.domain.config.GlobalParamDomain;
import com.yeebo.enums.config.ParamNameEnums;
import com.yeebo.rpc.config.ConfigService;
import com.yeebo.utils.AliYunOSSUtils;
import com.yeebo.utils.IdUtils;
import net.coobird.thumbnailator.Thumbnails;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

@Service
public class ConfigServiceImpl implements ConfigService {
    private static Logger logger = LoggerFactory.getLogger(ConfigServiceImpl.class);

    @Resource
    private GlobalParamDomain globalParamDomain;
    @Resource
    private AliYunOSSUtils aliYunOSSUtils;

    @Override
    public String uploadImageFileToYunOSS(MultipartFile file) {
        String originalFileName = file.getOriginalFilename();
        String suffix = originalFileName.substring(originalFileName.lastIndexOf(".")).toLowerCase();
        String newFileName = IdUtils.getCurrentFileName() + suffix;
        String aliYunRootDirectory = globalParamDomain.getStringVal(ParamNameEnums.UPLOAD_FILE_PATH.getKey());
        String targetFilePath = aliYunRootDirectory + newFileName;

        // 判断是否需要压缩
        String compressFileType= globalParamDomain.getStringVal(ParamNameEnums.COMPRESS_FILE_TYPE.getKey());
        if (compressFileType.contains(suffix)) {
            try {
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                Thumbnails.of(file.getInputStream())
                        .scale(1f)
                        .outputQuality(0.5d)
                        .outputFormat("jpg").toOutputStream(outputStream);
                return aliYunOSSUtils.putInputStreamAndGetUrl(new ByteArrayInputStream(outputStream.toByteArray()), targetFilePath);
            } catch (Exception ex) {
                logger.error("文件压缩出现错误，错误信息ex={}", ex);
            }
        }

        return aliYunOSSUtils.putFileAndGetUrl(file, targetFilePath);
    }
}
